<template>
  <el-form :model="formData" :label-width="labelWidth" ref="form">
    <el-form-item
      v-for="(item, index) in formItem"
      :key="index"
      :label="item.label"
      :prop="item.prop"
      :rules="item.rules"
    >
      <!-- 输入框 -->
      <el-input
        v-model.trim="formData[item.prop]"
        :disabled="item.disabled"
        v-if="item.type === 'Input'"
        :placeholder="item.placeholder"
      ></el-input>

      <el-select
        v-if="item.type === 'Select'"
        v-model="formData[item.prop]"
        :placeholder="item.placeholder"
      >
        <el-option
          v-for="(key, index) in item.options"
          :key="index"
          :value="key[item._valueType]"
        ></el-option>
      </el-select>
      <el-radio-group
        v-if="item.type === 'Radio'"
        v-model="formData[item.prop]"
      >
        <el-radio
          v-for="(item, index) in item.options"
          :label="item.value"
          :key="index"
          >{{ item.label }}</el-radio
        >
      </el-radio-group>
      <template v-else-if="item.type === 'Slot'">
        <slot :name="item.slotName"></slot>
      </template>
    </el-form-item>
    <!-- 按钮 -->
    <el-form-item v-if="formHandler.length > 0">
      <el-button
        v-for="(item, index) in formHandler"
        :key="index"
        :type="item.type"
        @click="item.handler && item.handler()"
        >{{ item.label }}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "vueForm",
  props: {
    formData: {
      type: Object,
      default: () => {},
    },
    formItem: {
      type: Array,
      default: () => [],
    },
    formHandler: {
      type: Array,
      default: () => [],
    },
    labelWidth: {
      type: String,
      default: () => "120px",
    },
  },
  data() {
    return {
      form: {},
    };
  },
  methods: {
    initFormData() {
      const formData = {};
      const formItem = this.formItem;
      for (let i = 0; i < formItem.length; i++) {
        let item = formItem[i];
        if (item.prop) {
          formData[item.prop] = item.value || null;
        }
        if (item.required) this.rules(item);
        if (item.validator && item.validator.length > 0)
          item.rules = item.validator;
      }
      this.form = formData;
    },
    // rules 规则
    rules(item) {
      const rulesMessage = {
        Input: "请输入",
        Radio: "请选择",
      };
      const requiredRules = [
        {
          required: true,
          message: item.rulesMsg || `${rulesMessage[item.type]}${item.label}`,
          trigger: item.trigger,
        },
      ];
      if (item.rules && item.rules.length > 0) {
        item.rules = requiredRules.concat(item.rules);
      } else {
        item.rules = requiredRules;
      }
    },
  },
  watch: {
    formItem: {
      handler() {
        this.initFormData();
      },
      immediate: true,
    },
  },
};
</script>

<style>
</style>